'use strict';
app.controller('postageCtrl', ['$scope','$state','toaster','$modal','postageService', function($scope,$state,toaster,$modal,postageService) {
    //查询全部地区
    $scope.postageTemplateVO={};

    $scope.app.loading=false;

    $scope.findTemplate=function(){
        if($scope.app.loading){
            return;
        }

        $scope.app.loading=true;

        postageService.findTemplate($scope).then(function(result){
            switch (result.status){
                case 200:
                    $scope.app.loading=false;

                    $scope.list = result.data;
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }

    $scope.findTemplate();


    $scope.del=function(id){
        postageService.del($scope,id).then(function(result){
            switch (result.status){
                case 200:
                    $scope.findTemplate();
                    toaster.pop('success', "提示", "操作成功");
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }



}]);


app.controller('postageAddCtrl', ['$scope','$state','toaster','$modal','postageService', function($scope,$state,toaster,$modal,postageService) {

    $scope.area={};
    var true_val=1;
    var false_val=0;

    //打开窗口
    $scope.openPoups = function (item) {

        $scope.merge($scope.area,item,true_val,false_val);

        var modalInstance = $modal.open({
            templateUrl: 'tpl/postage/postage_add_popup.html',
            controller: 'postageAddPopupsCtrl',
            size: 'lg',
            scope:$scope,
            resolve: {
                postcon:function(){
                    return item;
                }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            console.info('Modal dismissed at: ' + new Date());
        });
    };

    //查询全部地区
    $scope.findArea=function(){
        postageService.findArea($scope).then(function(result){
            switch (result.status){
                case 200:
                    $scope.area = result.data;
                    $scope.province=$scope.area.children;
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }

    $scope.findArea();

    $scope.postageConditionJson=new Array();

    //输入区域
    var pushArea=function(){
        var obj=new Object();
        obj.basicQuality=1.0;
        obj.basicPostage=0.0;
        obj.incrementQuality=1.0;
        obj.incrementPostage=0.0;
        $scope.postageConditionJson.push(obj);
    }

    pushArea();

    //添加区域信息
    $scope.addArea=function(){
        if($scope.postageConditionJson.length>0){
            var lastObj=$scope.postageConditionJson[$scope.postageConditionJson.length - 1];
            if(lastObj.areaJson==null){
                alert("请选择区域范围");
                return;
            }
        }
        pushArea();
    }

    $scope.deleteArea= function (index,item) {
        $scope.merge($scope.area,item,false_val,false_val);
        $scope.postageConditionJson.splice(index,1);
        if($scope.postageConditionJson.length<=0){
            alert("必须保存一个运费模板区域信息");
            pushArea();
        }
    }

    //tree
    $scope.merge=function(data,item,selectState,disabledState){
        var tree=new multiTree();
        if(item.areaJson){
            tree.merge(data,item.areaJson,selectState,disabledState);
        }
    }

    //多叉树
    //1.深度优先遍历的递归写法
    function multiTree(){
    }

    multiTree.prototype={
        //深度优先遍历
        traverseDF:function(node,callback){
            var len=0;

            if(node!=null){
                callback(node);
                for(var i=0;i<node.children.length;i++){
                    this.traverseDF(node.children[i],callback);
                    if(node.children[i].disabled==1){
                        len++;
                    }
                }

                if(len>0){
                    node.disabled=1;
                }
            }
        },
        //执行参数
        contains:function(callback,node,traversal) {
            traversal.call(this,node,callback);
        },
        //合并
        merge:function(node,data,selectState,disabledState){
            var root=new Object();
            root.children=data;
            var _this_=this;
            if(data){
                this.contains(function(node){
                    var index=data.indexOf(node.cityId);
                    if(index!=-1){
                        node.select=selectState;
                        node.disabled=disabledState;
                    }


                },node,this.traverseDF);
            }
        }

    }


    //保存模板
    $scope.postageTemplateJson={valuateType:0};

    $scope.add=function(){

        for(var i=0;i<$scope.postageConditionJson.length;i++) {
            if (!$scope.postageConditionJson[i].areaJson) {
                alert("请选择具体的地址区域");
                return;
            }
        }

        for(var i=0;i<$scope.postageConditionJson.length;i++){
            $scope.postageConditionJson[i].areaCode=$scope.postageConditionJson[i].areaJson.join(',');
            $scope.postageConditionJson[i].areaJson=JSON.stringify($scope.postageConditionJson[i].areaJson);
        }

        $scope.postageTemplateJson.postageConditionAddVOs=JSON.stringify($scope.postageConditionJson);

        postageService.add($scope).then(function(result){
            switch (result.status){
                case 200:
                    $state.go("app.postage");
                    toaster.pop('success', "提示", "操作成功");
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }



}]);


app.controller('postageEditCtrl', ['$scope','$state','$stateParams','toaster','$modal','postageService', function($scope,$state,$stateParams,toaster,$modal,postageService) {
    $scope.postageTemplateVO={id:$stateParams.id};
    $scope.postageConditionJson=new Array();
    $scope.postageTemplateJson={valuateType:0};
    $scope.area={};
    var true_val=1;
    var false_val=0;

    $scope.findTemplateBO=function(){
        postageService.findTemplateBO($scope).then(function(result){
            switch (result.status){
                case 200:
                    $scope.postageTemplateJson = result.data;
                    $scope.postageConditionJson=$scope.postageTemplateJson.childrens;
                    for(var i=0;i<$scope.postageConditionJson.length;i++){
                        $scope.postageConditionJson[i].areaJson=JSON.parse($scope.postageConditionJson[i].areaJson);

                        $scope.merge($scope.area,$scope.postageConditionJson[i],false_val,true_val);
                    }
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }

    $scope.findTemplateBO();



    //打开窗口
    $scope.openPoups = function (item) {

        $scope.merge($scope.area,item,true_val,false_val);

        var modalInstance = $modal.open({
            templateUrl: 'tpl/postage/postage_add_popup.html',
            controller: 'postageAddPopupsCtrl',
            size: 'lg',
            scope:$scope,
            resolve: {
                postcon:function(){
                    return item;
                }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            console.info('Modal dismissed at: ' + new Date());
        });
    };

    //查询全部地区
    $scope.findArea=function(){
        postageService.findArea($scope).then(function(result){
            switch (result.status){
                case 200:
                    $scope.area = result.data;
                    $scope.province=$scope.area.children;
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }

    $scope.findArea();

    //输入区域
    var pushArea=function(){
        var obj=new Object();
        obj.basicQuality=1.0;
        obj.basicPostage=0.0;
        obj.incrementQuality=1.0;
        obj.incrementPostage=0.0;
        $scope.postageConditionJson.push(obj);
    }

    //添加区域信息
    $scope.addArea=function(){
        if($scope.postageConditionJson.length>0){
            var lastObj=$scope.postageConditionJson[$scope.postageConditionJson.length - 1];
            if(lastObj.areaJson==null){
                alert("请选择区域范围");
                return;
            }
        }
        pushArea();
    }

    $scope.deleteArea= function (index,item) {
        $scope.merge($scope.area,item,false_val,false_val);
        $scope.postageConditionJson.splice(index,1);
        if($scope.postageConditionJson.length<=0){
            alert("必须保存一个运费模板区域信息");
            pushArea();
        }
    }

    //tree
    $scope.merge=function(data,item,selectState,disabledState){
        var tree=new multiTree();
        if(item.areaJson){
            tree.merge(data,item.areaJson,selectState,disabledState);
        }
    }

    //多叉树
    //1.深度优先遍历的递归写法
    function multiTree(){
    }

    multiTree.prototype={
        //深度优先遍历
        traverseDF:function(node,callback){
            var len=0;

            if(node!=null){
                callback(node);
                for(var i=0;i<node.children.length;i++){
                    this.traverseDF(node.children[i],callback);
                    if(node.children[i].disabled==1){
                        len++;
                    }
                }

                if(len>0){
                    node.disabled=1;
                }
            }
        },
        //执行参数
        contains:function(callback,node,traversal) {
            traversal.call(this,node,callback);
        },
        //合并
        merge:function(node,data,selectState,disabledState){
            var root=new Object();
            root.children=data;
            var _this_=this;
            if(data){
                this.contains(function(node){
                    var index=data.indexOf(node.cityId);
                    if(index!=-1){
                        node.select=selectState;
                        node.disabled=disabledState;
                    }

                },node,this.traverseDF);
            }
        }
    }


    //保存模板

    $scope.edit=function(){
        for(var i=0;i<$scope.postageConditionJson.length;i++) {
            if (!$scope.postageConditionJson[i].areaJson) {
                alert("请选择具体的地址区域");
                return;
            }
        }


        for(var i=0;i<$scope.postageConditionJson.length;i++){
            $scope.postageConditionJson[i].areaCode=$scope.postageConditionJson[i].areaJson.join(',');
            $scope.postageConditionJson[i].areaJson=JSON.stringify($scope.postageConditionJson[i].areaJson);
        }

        $scope.postageTemplateJson.postageConditionAddVOs=JSON.stringify($scope.postageConditionJson);

        postageService.edit($scope).then(function(result){
            switch (result.status){
                case 200:
                    $state.go("app.postage");
                    toaster.pop('success', "提示", "操作成功");
                    break;
                case 664:
                    toaster.pop('waiting', "提示", result.message);
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }



}]);

app.controller('postageAddPopupsCtrl', ['$scope', '$modalInstance','postageService','toaster',"postcon",function($scope, $modalInstance,postageService,toaster,postcon) {

    var backUpData=new Object();
    angular.copy($scope.area,backUpData);


    //取消
    $scope.cancel = function () {
        if(postcon.areaContent){
            postcon.areaContent="";
            var arr=new Array();
            choose($scope.area,arr);
            postcon.areaJson=arr;
        }

        $modalInstance.dismiss('cancel');
    };

    //展示市区
    $scope.showCity=function(item){
        $scope.city=item.children;
        $scope.county=[];
    }

    //展示县区
    $scope.showCounty=function(item){
        $scope.county=item.children;
    }


    //选择区域
    $scope.isCheck=function(item){
        if(typeof (item)=='undefined'){
            return;
        }

        if(item.children.length==0){
            return item.select==1;
        }else{
            var selectLen=0;
            for(var i=0;i<item.children.length;i++){
                if(item.children[i].select==1){
                    selectLen++;
                }
            }
            item.select=(selectLen>0)?1:0;
            return selectLen>0;
        }
    }


    $scope.updateSelection=function($event,item){
        var checkbox = $event.target ;
        item.select=checkbox.checked?1:0;
        selectItem(item);
    }

    var selectItem=function(item){
        for(var i=0;i<item.children.length;i++){
            item.children[i].select=item.select;

            if(item.children[i].disabled == 1){
                item.children[i].select = 0;
            }

            if(item.children[i].children.length>0){
                selectItem(item.children[i]);
            }
        }
    }

    //确认
    //$scope.areaSelect=[];
    $scope.ok=function(){
        postcon.areaContent="";


        var arr=new Array();
        choose($scope.area,arr);
        postcon.areaJson=arr;

        $modalInstance.dismiss('cancel');
    }

    //选择区域
    var choose=function(item,arr,str){
        var count=0;
        var list=new Array();

        for(var i=0;i<item.children.length;i++){
            if(item.children[i].select==1){
                list.push(item.children[i].cityId);
                choose(item.children[i],list,str);
                item.children[i].disabled=1;

                count++;
            }

            item.children[i].select=0;
            selectItem(item.children[i]);
        }


        if(item.label!="root"){
            //var label="";
            //if(count==item.children.length && item.children.length!=0){
            //    label="[全境]";
            //}
            postcon.areaContent=item.label+postcon.areaContent;
        }

        arr.unshift.apply(arr,list);
    }



}]);

app.directive("postageTree", function() {
    return {
        restrict: "E",
        scope: {
            data: '='
        },
        templateUrl: 'tpl/postage/postage_tree.html',
        controller: function ($scope) {
        }
    };
});